package org.dh2580.netty.demo.netty.serializable.jdk;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.alibaba.fastjson.JSON;

/**
 * RPC服务框架不使用JDK Serializable 原因
 * <p>
 *      1、无法跨语言：Java序列化是Java语言内部的私有协议，其他语言不支持
 *      2、序列化后的码流太大：采用JDK序列化机制编码后的二进制数组大小是二进制编码的约5倍
 *      3、序列化性能极差：速度是普通二进制编码的7%左右
 * </p>
 * @Author: hao.deng
 * @Date: 2019/4/25-下午12:34
 */
public class JdkSerializable {
    public static void main(String[] args) throws IOException {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(100);
        userInfo.setName("Welcome to Netty");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        ObjectOutputStream os = new ObjectOutputStream(bos);
        os.writeObject(userInfo);
        os.flush();
        os.close();

        byte[] bytes = bos.toByteArray();
        System.out.println("The jdk serializable length is " + bytes.length);
        bos.close();

        System.out.println(JSON.toJSONString(userInfo).length());
    }

    public static class UserInfo implements Serializable {

        private static final long serialVersionUID = 4848575795864339104L;
        private int id;
        private String name;

        public UserInfo() {
        }

        public UserInfo(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

}
